package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.view.SignatureView;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class SugnatureActivity extends SwipeBackActivity implements View.OnClickListener {
    private EditText mContainer;
    private SignatureView mSignView;
    private List<Bitmap> bitmaps = new ArrayList<>();
    private List<File> uploadFiles = new ArrayList<>();
    private TextView tv;

    private Button button,mybutton;
    private String path;
    private LinearLayout imageView;

    private int ecCode;
    private String TAG="SugnatureActivity";

    public static final String APP_NAME = "linghuilv";
    public String DATE = "";
    public static final String PICTURE_DIR = Environment.getExternalStorageDirectory() + "/pictures/";
    public static String createImagePath(String imageName) {
        String dir = PICTURE_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(imageName)) {
            file = new File(dir, imageName + ".jpeg");
        }
        return file.getAbsolutePath();
    }


    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sugnature);
        setStatusBar();
       // mContainer = (EditText) findViewById(R.id.ll_container);
        mSignView = (SignatureView) findViewById(R.id.id_sign);
       // tv= (TextView) findViewById(R.id.tv);
        disableShowSoftInput(mContainer);
        button= (Button) findViewById(R.id.sign_doup);
        button.setOnClickListener(this);
        mybutton= (Button) findViewById(R.id.button_sing_back);
        mybutton.setOnClickListener(this);
        imageView= (LinearLayout) findViewById(R.id.sing_back);
        imageView.setOnClickListener(this);
        mSignView.setSignatureCallBack(new SignatureView.ISignatureCallBack() {
            @Override
            public void onSignCompeleted(View view, Bitmap bitmap) {
               // createImagePath(APP_NAME+"sign");
                String fileDir=Environment.getExternalStorageDirectory() + "/pictures/";
                path=fileDir+"linghuilvsign"+".png";
                File file=new File(fileDir);
                if(!file.exists()){
                    file.mkdir();
                }
                bitmaps.add(bitmap);
                try {
                    mSignView.save(path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                uploadFiles.add(new File(path));
                drawBitmaps(bitmap);
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.sign_doup:
                mSignView.onFinish();
                if(uploadFiles!=null){
                    toSiging(path);
                }
                break;
            case R.id.button_sing_back:
                finish();
                break;
            case R.id.sing_back:
                finish();
                break;
        }
    }
    private void showFiles() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("sign_image",path);
        editor.commit();
    }

    private void drawBitmaps(Bitmap b) {
        ImageSpan imgSpan = new ImageSpan(this, b);
        SpannableString spanString = new SpannableString("i");
        spanString.setSpan(imgSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
       // mContainer.append(spanString);
    }

//    public void delete(View view) {
//        if(bitmaps.size()>0){
//            bitmaps.remove(bitmaps.size()-1);
//            File file=uploadFiles.get(uploadFiles.size()-1);
//            uploadFiles.remove(file);
//            file.delete();
//        //    deleteText(mContainer);
//            showFiles();
//        }
//    }

    /**
     * 获取EditText光标所在的位置
     */
    private int getEditTextCursorIndex(EditText mEditText) {
        return mEditText.getSelectionStart();
    }

    /**
     * 向EditText指定光标位置删除字符串
     */
    private void deleteText(EditText mEditText) {
        Log.e("TAG", mEditText.getText().toString());
        if (!TextUtils.isEmpty(mEditText.getText().toString())) {
            mEditText.getText().delete(getEditTextCursorIndex(mEditText) - 1, getEditTextCursorIndex(mEditText));
        }
    }

    public static void disableShowSoftInput(EditText editText) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            editText.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method method;
            try {
                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(editText, false);
            } catch (Exception e) {
                // TODO: handle exception
            }

            try {
                method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(editText, false);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }


    private void toSiging(String path){

        SharedPreferences sharedPreferences =getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params1 = new RequestParams("http://zljl.laiima.com/index.php?s=/hjs_api/Real/sign");
        //需要带入的参数
        params1.setMultipart(true);
        params1.addBodyParameter("uid", userID);
        params1.addBodyParameter("sign", new File(path),".png");
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ecCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "回调成功"+ecCode);
                if (ecCode == 200) {
                    showFiles();
                    Log.e(TAG, "签约成功");
                    DATE = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                    SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("Signing", "false");
                    editor.putString("Sig_date", DATE);
                    editor.commit();
                    Toast.makeText(getBaseContext().getApplicationContext(), "签约成功", Toast.LENGTH_SHORT).show();
                    Intent userintent=new Intent(getBaseContext().getApplicationContext(),ElectroniContractActivity.class);
                    startActivity(userintent);
                }
                if (ecCode == 201) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "签约失败，请先实名认证", Toast.LENGTH_SHORT).show();
                 }
                if (ecCode == 203) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "上传图片", Toast.LENGTH_SHORT).show();
                }
                if (ecCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                        Intent Nameintent=new Intent(HomeActivity.this,NameActivity.class);
//                        startActivity(Nameintent);
                Log.e(TAG, "查看实名认证失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {


            }
        });
    }


}
